package com.jason.common.video;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * TODO
 *
 * @author gzc
 * @since 2023/12/28 17:18
 **/
@Slf4j
public class Test {
    public static void main(String[] args) throws Exception {
        long l = 1024L * 1000L / 48000L;
        System.out.println(l);
        if (true) {
            return;
        }
        String videoFile = "E:\\javacv-test\\Lolita(1997).mkv";
        // 读取视频
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoFile);
//        grabber.setOption("rtsp_transport", "tcp");
//        grabber.setFormat("rtsp");
        grabber.start();
        int width = grabber.getImageWidth();
        int height = grabber.getImageHeight();
        double frameRate = grabber.getFrameRate();

        int ftp = grabber.getLengthInFrames();
        int flag = 0;
        Frame frame = null;
        while (grabber.grabFrame() != null) {
            // 对每一帧进行处理
            //获取帧
            frame = grabber.grabImage();
            //过滤前 second 帧，避免出现全黑图片
            if ((flag > 10) && (frame != null)) {
                break;
            }
            flag++;
        }
        // 创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        String newFileName = "E:\\javacv-test\\ggg-im2.jpg";
        File file = FileUtil.touch(newFileName);
        ImageIO.write(bufferedImage, "jpg", file);
        grabber.close();
        grabber.stop();

        // 输出视频
//        String outputFile = "E:\\javacv-test\\ggg-1.mp4";
//        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, width, height);
//        recorder.setFormat("mp4");
//        recorder.setFrameRate(frameRate);
//        recorder.start();
//
//        // 对每一帧进行处理后，写入到输出文件中
//        recorder.record(frame);
        grabber.stop();
//        recorder.stop();
        System.out.println(StrUtil.format("视频高度:{}, 视频宽度:{}, 视频帧率:{}", height, width, frameRate));
    }

}
